﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
using ThoughtWorks.QRCode.Codec;

//ASP.net(c#)生成条形码

namespace YTBZ.PUB.Common
{

    public class BarCode1
    {
        public BarCode1()
        {
            //构造函数

        }
        public static string  GeBarCodeImage(string FilePath,string BarCode)
        {
            QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
            string strFilePath = "";
            #region 设置条形码图片
            if (!string.IsNullOrEmpty(BarCode.Trim()))
            {
                string strFolder = "";
                Bitmap image;
                String data = BarCode.Trim().TrimStart('0');
                if (data.Length >= 1 && data[0] >= 'A' && data[0] <= 'z')
                    strFolder = data.Substring(0, 1) + "\\";
                else if (data.Length >= 4 && data[0] >= '0' && data[0] <= '9')
                    strFolder = data.Substring(0, 4) + "\\";
                strFilePath = FilePath + "ERWEIMA\\" + strFolder;
                if (!Directory.Exists(strFilePath))
                {
                    Directory.CreateDirectory(strFilePath);
                }
                strFilePath = strFilePath + data + ".bmp";

                String encoding = "AlphaNumeric";
                if (encoding == "Byte")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                }
                else if (encoding == "AlphaNumeric")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
                }
                else if (encoding == "Numeric")
                {
                    qrCodeEncoder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.NUMERIC;
                }

                string errorCorrect = "L";
                if (errorCorrect == "L")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
                else if (errorCorrect == "M")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                else if (errorCorrect == "Q")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
                else if (errorCorrect == "H")
                    qrCodeEncoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H;
                try
                {
                    if (!File.Exists(strFilePath.Trim()))
                    {
                        image = qrCodeEncoder.Encode(data);
                        image.Save(strFilePath, ImageFormat.Bmp);
                        image.Dispose();
                    }

                    //string XDBH = BarCode;
                    //strFilePath = FilePath + "Code39Img" + flwslb + "\\" + XDBH + ".bmp";
                    //if (!File.Exists(strFilePath.Trim()))
                    //{
                    //    BarCode.GetBarCodeBitmap("Code39", XDBH, strFilePath, iHight, iy, isShowNum);   //code39码
                    //}
                    //Byte[] fileDate = null;
                    //SupFile m_file = new SupFile(strFilePath);
                    //fileDate = m_file.GetFileByte();
                    //dtIn.Rows[i]["BarCode1"] = fileDate;
                }
                catch { /*dtIn.Rows[i]["BarCode1"] = null;*/ }
            }
            //else
            //    dtIn.Rows[i]["BarCode1"] = null;
            #endregion
            return strFilePath;
        }
        /// <summary>
        /// 生成条形码图片，支持code39,code93,code128三种
        /// </summary>
        /// <param name="CodeMode">类型：code39,code93,code128C </param>
        /// <param name="mycode">条码值</param>
        /// <param name="strFilePath">图片保存路径</param>
        /// <param name="iHight">畫布高</param>
        /// <param name="iy">筆 y</param>
        /// <param name="isShowNum">code93是否显示数字  code39\128显示方式true横false竖</param> 
        public static void GetBarCodeBitmap(string CodeMode, string mycode, string strFilePath, int iHight, int iy, bool isShowNum)
        {
            switch (CodeMode.ToLower())
            {
                case "code39_1":
                    GetBarCodeBitmap_Code39_1(mycode, strFilePath, iHight, iy, isShowNum);
                    break;
                case "code39": //可行
                    if (isShowNum)
                    {
                        GetBarCodeBitmap_Code39(mycode, strFilePath, iHight, iy, isShowNum);
                    }
                    else GetBarCodeBitmapZ90_Code39(mycode, strFilePath, iHight, iy, isShowNum);
                    break;
                case "code128c":
                    GetBarCodeBitmap_Code128(mycode, strFilePath, iHight, isShowNum);
                    break;
                case "code128a":  //可行
                    if (!string.IsNullOrEmpty(mycode))
                    {
                        Code128 code128A = new Code128();
                        Bitmap BMP128A = code128A.GetCodeImage(mycode, Code128.Encode.Code128A, isShowNum);
                        string Folder = strFilePath.Remove(strFilePath.LastIndexOf("\\"));
                        if (!Directory.Exists(Folder))//判断文件夹是否存在
                        {
                            Directory.CreateDirectory(Folder);
                        }
                        BMP128A.Save(strFilePath, ImageFormat.Jpeg);
                        BMP128A.Dispose();
                    }
                    break;
                case "code128b": //可行
                    if (!string.IsNullOrEmpty(mycode))
                    {
                        Code128 code128B = new Code128();
                        Bitmap BMP128B = code128B.GetCodeImage(mycode, Code128.Encode.Code128B, isShowNum);
                        BMP128B.Save(strFilePath, ImageFormat.Jpeg);
                        BMP128B.Dispose();

                    } break;
                case "ean128":
                    if (!string.IsNullOrEmpty(mycode))
                    {
                        Code128 ean128 = new Code128();
                        Bitmap BMPean128 = ean128.GetCodeImage(mycode, Code128.Encode.EAN128, isShowNum);
                        BMPean128.Save(strFilePath, ImageFormat.Jpeg);
                        BMPean128.Dispose();

                    } break;
                case "code128c2":  
                    if (!string.IsNullOrEmpty(mycode))
                    {
                        Code128 code128C = new Code128();
                        Bitmap BMP128C = code128C.GetCodeImage(mycode, Code128.Encode.Code128C, isShowNum);
                        BMP128C.Save(strFilePath, ImageFormat.Jpeg);
                        BMP128C.Dispose();
                    } break;
                default: break;
            }
        }

        #region GetBarcode Html 条码
        public string GetBarcode(object str, int ch, int cw, int type_code)
        {
            //str:输入的字符串;ch:要显示条形码的高度;cw:要显示条形码的宽度;type_code:代码类型
            string strTmp = str.ToString();
            string code = strTmp;
            // ToLower()将string转化成小写形式的副本，返回是使用指定区域的性的大小写规则。
            strTmp = strTmp.ToLower();
            int height = ch;
            int width = cw;

            #region //将传入的参数进行转化。
            strTmp = strTmp.Replace("0", "_|_|__||_||_|"); ;
            strTmp = strTmp.Replace("1", "_||_|__|_|_||");
            strTmp = strTmp.Replace("2", "_|_||__|_|_||");
            strTmp = strTmp.Replace("3", "_||_||__|_|_|");
            strTmp = strTmp.Replace("4", "_|_|__||_|_||");
            strTmp = strTmp.Replace("5", "_||_|__||_|_|");
            strTmp = strTmp.Replace("7", "_|_|__|_||_||");
            strTmp = strTmp.Replace("6", "_|_||__||_|_|");
            strTmp = strTmp.Replace("8", "_||_|__|_||_|");
            strTmp = strTmp.Replace("9", "_|_||__|_||_|");
            strTmp = strTmp.Replace("a", "_||_|_|__|_||");
            strTmp = strTmp.Replace("b", "_|_||_|__|_||");
            strTmp = strTmp.Replace("c", "_||_||_|__|_|");
            strTmp = strTmp.Replace("d", "_|_|_||__|_||");
            strTmp = strTmp.Replace("e", "_||_|_||__|_|");
            strTmp = strTmp.Replace("f", "_|_||_||__|_|");
            strTmp = strTmp.Replace("g", "_|_|_|__||_||");
            strTmp = strTmp.Replace("h", "_||_|_|__||_|");
            strTmp = strTmp.Replace("i", "_|_||_|__||_|");
            strTmp = strTmp.Replace("j", "_|_|_||__||_|");
            strTmp = strTmp.Replace("k", "_||_|_|_|__||");
            strTmp = strTmp.Replace("l", "_|_||_|_|__||");
            strTmp = strTmp.Replace("m", "_||_||_|_|__|");
            strTmp = strTmp.Replace("n", "_|_|_||_|__||");
            strTmp = strTmp.Replace("o", "_||_|_||_|__|");
            strTmp = strTmp.Replace("p", "_|_||_||_|__|");
            strTmp = strTmp.Replace("r", "_||_|_|_||__|");
            strTmp = strTmp.Replace("q", "_|_|_|_||__||");
            strTmp = strTmp.Replace("s", "_|_||_|_||__|");
            strTmp = strTmp.Replace("t", "_|_|_||_||__|");
            strTmp = strTmp.Replace("u", "_||__|_|_|_||");
            strTmp = strTmp.Replace("v", "_|__||_|_|_||");
            strTmp = strTmp.Replace("w", "_||__||_|_|_|");
            strTmp = strTmp.Replace("x", "_|__|_||_|_||");
            strTmp = strTmp.Replace("y", "_||__|_||_|_|");
            strTmp = strTmp.Replace("z", "_|__||_||_|_|");
            strTmp = strTmp.Replace("-", "_|__|_|_||_||");
            strTmp = strTmp.Replace("*", "_|__|_||_||_|");
            strTmp = strTmp.Replace("/", "_|__|__|_|__|");
            strTmp = strTmp.Replace("%", "_|_|__|__|__|");
            strTmp = strTmp.Replace("+", "_|__|_|__|__|");
            strTmp = strTmp.Replace(".", "_||__|_|_||_|");
            strTmp = strTmp.Replace("_", "<span style='height:" + height + ";width:" + width + ";background:#FFFFFF;'></span>");
            strTmp = strTmp.Replace("|", "<span style='height:" + height + ";width:" + width + ";background:#000000;'></span>");
            #endregion
            if (type_code == 1)
            {
                return strTmp + "<BR>" + code;
            }
            else
            {
                return strTmp;
            }
        }

        //方法二：
        public Bitmap CreateCodeLogo(string code)
        {

            long len = code.Length;
            string lastString = "";
            char[] list = new char[len + 1];


            list = code.ToCharArray();

            for (int i = 0; i < list.Length; i++)
            {
                lastString += this.ConvertToBinaryString(list[i].ToString());
            }

            char[] numList = new char[lastString.Length + 1];
            numList = lastString.ToCharArray();


            Bitmap image = new Bitmap(200, 140);
            Graphics g = Graphics.FromImage(image);

            g.Clear(Color.White);

            Pen penBlack = new Pen(Color.FromArgb(255, 0, 0, 0), 2.5F);
            Pen penWhite = new Pen(Color.White, 2.5F);

            int j = 0;

            for (float k = 10; j < numList.Length; k += 2F, j++)
            {
                if (numList[j].ToString() == "1")
                {
                    g.DrawLine(penBlack, k, 10, k, 110);

                }
                else
                {
                    g.DrawLine(penWhite, k, 10, k, 110);
                }

                if (j % 4 == 0)
                {
                    g.DrawString(list[j / 4].ToString(), new System.Drawing.Font("Courier New", 12), new SolidBrush(Color.Red), k, 112);
                }
            }
            return image;// image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
        }
        public void CreateCodeLogoimg(string code)
        {
            //Bitmap image = new Bitmap(200, 140);
            //Graphics g = Graphics.FromImage(image);

            //image = CreateCodeLogo(code);
            //image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
        }

        //将字符串数值转换为二进制字符串数值
        public string ConvertToBinaryString(string buf)
        {
            int[] temp = new int[20];
            string binary;
            int val = 0, i = 0, j;

            //先将字符转化为十进制数
            try
            {
                val = Convert.ToInt32(buf);
            }
            catch
            {
                val = 0;
            }

            if (val == 0)
            {
                return ("0000");
            }

            i = 0;
            while (val != 0)
            {
                temp[i++] = val % 2;
                val /= 2;
            }

            binary = "";

            for (j = 0; j <= i - 1; j++)
            {
                binary += (char)(temp[i - j - 1] + 48);
            }

            if (binary.Length < 4)   //如果小于4位左边补零
            {
                int len = 4 - binary.Length;
                string str = "";

                while (len > 0)
                {
                    str += "0";
                    len--;
                }

                binary = str + binary;
            }

            return (binary);
        }
        #endregion

        #region    GetBarCodeBitmap_Code39 条形码图片 Code39码
        /// <summary>
        /// 生成条形码图片
        /// </summary>
        /// <param name="mycode">条码值</param>
        /// <param name="strFilePath">图片保存路径</param>
        /// <param name="iHight">畫布高</param>
        /// <param name="iy">筆 y</param>
        /// <param name="isShowNum">是否显示数字</param>
        /// <returns></returns>
        public static string GetBarCodeBitmap_Code39(string mycode, string strFilePath, int iHight, int iy, bool isShowNum)
        {
            //string strFilePath = HttpContext.Current.Application["XDDYFolder"].ToString().Trim('\\') + "\\Code39Img\\" + mycode + ".jpg";

            string strZC;//字串
            string strZY;//字元
            //strZC = "*-%$*"
            strZC = "*" + mycode + "*";  //Code 39 的特性是前、後置碼會標識「星號(*)」，表示開始和結束

            //int iHight = 60;  //畫布高
            int iWidth = 0;   //畫布寬
            int ix = 0;      //筆 x
            //int iy = 40;     //筆 y
            //int 筆寬 = 0;

            if (!string.IsNullOrEmpty(mycode))
            {
                iWidth = strZC.Length * 13;

                Bitmap BMP = new Bitmap(iWidth, iHight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.TextRenderingHint = TextRenderingHint.AntiAlias;
                G.Clear(Color.White);

                Brush brush1 = new SolidBrush(Color.White);
                G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                G.FillRectangle(brush1, 0, 0, iWidth, iHight);

                for (int i = 0; i < strZC.Length; i++)
                {
                    //取得 Code 39 碼的規則
                    strZY = genBarcode(strZC.Substring(i, 1).ToUpper());

                    for (int j = 0; j < 4; j++)
                    {
                        if (strZY.Substring(j, 1).Equals("0"))
                        {
                            G.DrawLine(Pens.Black, ix, 0, ix, iy);
                        }
                        else
                        {
                            G.DrawLine(Pens.Black, ix, 0, ix, iy);
                            G.DrawLine(Pens.Black, ix + 1, 0, ix + 1, iy);
                            ix += 1;
                        }

                        ix += 1;

                        if (strZY.Substring(j + 5, 1).Equals("0"))
                        {
                            G.DrawLine(Pens.White, ix, 0, ix, iy);
                        }
                        else
                        {
                            G.DrawLine(Pens.White, ix, 0, ix, iy);
                            G.DrawLine(Pens.White, ix + 1, 0, ix + 1, iy);
                            ix += 1;
                        }

                        ix += 1;
                    } //end of loop

                    if (strZY.Substring(4, 1).Equals("0"))
                    {
                        G.DrawLine(Pens.Black, ix, 0, ix, iy);
                    }
                    else
                    {
                        G.DrawLine(Pens.Black, ix, 0, ix, iy);
                        G.DrawLine(Pens.Black, ix + 1, 0, ix + 1, iy);
                        ix += 1;
                    }

                    ix += 2;
                } //end of loop
                if (!isShowNum) //是否显示数字
                {
                    int x = 0;
                    int addx = 13;

                    //G.DrawString("-", new Font("Arial", 10, FontStyle.Italic), SystemBrushes.WindowText, new PointF(x, 20));
                    x += addx;

                    for (int k = 0; k < mycode.Length; k++)
                    {
                        G.DrawString(mycode.Substring(k, 1), new Font("Arial", 10, FontStyle.Italic), SystemBrushes.WindowText, new PointF(x, iy));
                        x = x + addx;
                    }
                }
                //G.DrawString("-", new Font("Arial", 10, FontStyle.Italic), SystemBrushes.WindowText, new PointF(x, 20));
                string Folder = strFilePath.Remove(strFilePath.LastIndexOf("\\"));
                if (!Directory.Exists(Folder))//判断文件夹是否存在
                {
                    Directory.CreateDirectory(Folder);
                }
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 10);
                ps.Param[0] = p;

                //BMP.Save(Response.OutputStream, ImageFormat.Jpeg);
                BMP.Save(strFilePath, ImageFormat.Jpeg);
                //BMP.Save(strFilePath, GetCodecInfo("image/jpeg"), ps);
                G.Dispose();
                BMP.Dispose();
            }
            else
            {
                iWidth = 100;

                Bitmap BMP = new Bitmap(iWidth, iHight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.TextRenderingHint = TextRenderingHint.AntiAlias;
                G.Clear(Color.White);
                //未給參數時顯示的提示內容
                G.DrawString("无条码产生", new Font("宋体", 12, FontStyle.Regular), SystemBrushes.WindowText, new PointF(0, 20));
                //BMP.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                G.Dispose();

                BMP.Dispose();
            }
            return strFilePath;
        }

        public static string GetBarCodeBitmapZ90_Code39(string mycode, string strFilePath, int iWidth, int ix, bool isShowNum)
        {
            //string strFilePath = HttpContext.Current.Application["XDDYFolder"].ToString().Trim('\\') + "\\Code39Img\\" + mycode + ".jpg";

            string strZC;//字串
            string strZY;//字元
            //strZC = "*-%$*"
            strZC = "*" + mycode + "*";  //Code 39 的特性是前、後置碼會標識「星號(*)」，表示開始和結束

            int iHight = 0;  //畫布高
            //int iWidth = 60;   //畫布寬
            //int ix = 40;      //筆 x
            int iy = 0;     //筆 y
            //int 筆寬 = 0;

            if (!string.IsNullOrEmpty(mycode))
            {
                iHight = strZC.Length * 13;

                Bitmap BMP = new Bitmap(iWidth, iHight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.TextRenderingHint = TextRenderingHint.AntiAlias;
                G.Clear(Color.White);
                G.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //插值模式
                G.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;//文本呈现提示
                Brush brush1 = new SolidBrush(Color.White);
                G.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                G.FillRectangle(brush1, 0, 0, iWidth, iHight);

                for (int i = 0; i < strZC.Length; i++)
                {
                    //取得 Code 39 碼的規則
                    strZY = genBarcode(strZC.Substring(i, 1).ToUpper());

                    for (int j = 0; j < 4; j++)
                    {
                        if (strZY.Substring(j, 1).Equals("0"))
                        {
                            G.DrawLine(Pens.Black, 0, iy, ix, iy);
                        }
                        else
                        {
                            G.DrawLine(Pens.Black, 0, iy, ix, iy);
                            G.DrawLine(Pens.Black, 0, iy + 1, ix + 1, iy + 1);
                            iy += 1;
                        }

                        iy += 1;

                        if (strZY.Substring(j + 5, 1).Equals("0"))
                        {
                            G.DrawLine(Pens.White, 0, iy, ix, iy);
                        }
                        else
                        {
                            G.DrawLine(Pens.White, 0, iy, ix, iy);
                            G.DrawLine(Pens.White, 0, iy + 1, ix, iy + 1);
                            iy += 1;
                        }

                        iy += 1;
                    } //end of loop

                    if (strZY.Substring(4, 1).Equals("0"))
                    {
                        G.DrawLine(Pens.Black, 0, iy, ix, iy);
                    }
                    else
                    {
                        G.DrawLine(Pens.Black, 0, iy, ix, iy);
                        G.DrawLine(Pens.Black, 0, iy + 1, ix, iy + 1);
                        iy += 1;
                    }

                    iy += 2;
                } //end of loop

                string Folder = strFilePath.Remove(strFilePath.LastIndexOf("\\"));
                if (!Directory.Exists(Folder))//判断文件夹是否存在
                {
                    Directory.CreateDirectory(Folder);
                }
                EncoderParameter p;
                EncoderParameters ps;

                ps = new EncoderParameters(1);

                p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 10);
                ps.Param[0] = p;

                //BMP.Save(Response.OutputStream, ImageFormat.Jpeg);
                BMP.Save(strFilePath, ImageFormat.Jpeg);
                //BMP.Save(strFilePath, GetCodecInfo("image/jpeg"), ps);
                G.Dispose();
                BMP.Dispose();
            }
            else
            {
                iWidth = 100;

                Bitmap BMP = new Bitmap(iWidth, iHight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.TextRenderingHint = TextRenderingHint.AntiAlias;
                G.Clear(Color.White);

                //未給參數時顯示的提示內容
                G.DrawString("无条码产生", new Font("宋体", 12, FontStyle.Regular), SystemBrushes.WindowText, new PointF(0, 20));
                //BMP.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                G.Dispose();

                BMP.Dispose();
            }
            return strFilePath;
        }
        // 規則可參考網址 1：http://blog.csdn.net/xuzhongxuan/archive/2008/05/28/2489358.aspx
        // 規則可參考網址 2：http://blog.163.com/zryou/blog/static/6903184200971704226450/
        /// <summary>
        /// Code 39 碼的規則。
        /// Code 39 碼可使用的strZY如下：0~9、A~Z、+、-、*、/、%、$、. 及空白strZY。    
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string genBarcode(string code)
        {
            switch (code)
            {
                case "0":
                    code = "001100100";
                    break;
                case "1":
                    code = "100010100";
                    break;
                case "2":
                    code = "010010100";
                    break;
                case "3":
                    code = "110000100";
                    break;
                case "4":
                    code = "001010100";
                    break;
                case "5":
                    code = "101000100";
                    break;
                case "6":
                    code = "011000100";
                    break;
                case "7":
                    code = "000110100";
                    break;
                case "8":
                    code = "100100100";
                    break;
                case "9":
                    code = "010100100";
                    break;
                case "A":
                    code = "100010010";
                    break;
                case "B":
                    code = "010010010";
                    break;
                case "C":
                    code = "110000010";
                    break;
                case "D":
                    code = "001010010";
                    break;
                case "E":
                    code = "101000010";
                    break;
                case "F":
                    code = "011000010";
                    break;
                case "G":
                    code = "000110010";
                    break;
                case "H":
                    code = "100100010";
                    break;
                case "I":
                    code = "010100010";
                    break;
                case "J":
                    code = "001100010";
                    break;
                case "K":
                    code = "100010001";
                    break;
                case "L":
                    code = "010010001";
                    break;
                case "M":
                    code = "110000001";
                    break;
                case "N":
                    code = "001010001";
                    break;
                case "O":
                    code = "101000001";
                    break;
                case "P":
                    code = "011000001";
                    break;
                case "Q":
                    code = "000110001";
                    break;
                case "R":
                    code = "100100001";
                    break;
                case "S":
                    code = "010100001";
                    break;
                case "T":
                    code = "001100001";
                    break;
                case "U":
                    code = "100011000";
                    break;
                case "V":
                    code = "010011000";
                    break;
                case "W":
                    code = "110001000";
                    break;
                case "X":
                    code = "001011000";
                    break;
                case "Y":
                    code = "101001000";
                    break;
                case "Z":
                    code = "011001000";
                    break;
                case "*":
                    code = "001101000";
                    break;
                case "-":
                    code = "000111000"; //好像辨識不出來
                    break;
                case "%":
                    code = "100101000"; //好像辨識不出來
                    break;
                case "$":
                    code = "010101000"; //好像辨識不出來
                    break;
                default:
                    code = "010101000"; //都不是就印 $
                    break;
            }

            return code;
        }

        /// 保存JPG时用
        /// </summary>
        /// <param name="mimeType"></param>
        /// <returns>得到指定mimeType的ImageCodecInfo</returns>
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        #endregion

        #region GetBarCodeBitmap_Code128  条码 Code 128码

        /// <summary>
        /// 条形码生成函数Code 128码
        /// </summary> 
        /// <param name="mycode">条型码字串</param>
        /// <param name="strFilePath">图片路径</param>
        /// <param name="iWidth">条码宽度</param>
        /// <param name="isShowMode">显示方式true横false竖</param>
        /// <returns></returns>
        public static Bitmap GetBarCodeBitmap_Code128(string mycode, string strFilePath, int iWidth, bool isShowMode)
        {
            //string strFilePath = HttpContext.Current.Application["XDDYFolder"].ToString().Trim('\\') + "\\Code39Img\\" + mycode + ".jpg";

            string strZC;//字串
            //strZC = "*-%$*"
            strZC = "*" + mycode + "*";  //Code 39 的特性是前、後置碼會標識「星號(*)」，表示開始和結束
            Bitmap BMP=null;
            int iHight = 0;  //畫布高
            //int iWidth = 60;   //畫布寬
            //int ix = 40;      //筆 x
            //int 筆寬 = 0;

            if (!string.IsNullOrEmpty(mycode))
            {
                iHight = strZC.Length * 13;

                //Bitmap BMP = new Bitmap(iWidth, iHight, System.Drawing.Imaging.PixelFormat.Format32bppPArgb);
                 BMP = BuildBarCode128(mycode, iWidth, isShowMode);
                Encoder myEncoder= Encoder.Quality;               
                EncoderParameters myEncoderParameters=new EncoderParameters(1);
                // 保存位图的JPEG文件的质量水平25。 
                EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 75L);
                ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
                myEncoderParameters.Param[0] = myEncoderParameter;
                BMP.Save(strFilePath, myImageCodecInfo, myEncoderParameters);
                //BMP.Save(strFilePath, ImageFormat.Jpeg);
                //BMP.Save(strFilePath, GetCodecInfo("image/jpeg"), ps);

                BMP.Dispose();
            }

            return BMP;
        }
        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        /// <summary>
        /// 条形码生成函数
        /// </summary> 
        /// <param name="mycode">条型码字串</param>
        /// <param name="iHight">高或宽</param>
        /// <param name="isShowMode">显示方式true横false竖</param>
        /// <returns></returns>
        public static Bitmap BuildBarCode128(string mycode, int iHight, bool isShowMode)
        {

            //查检是否合条件TEXT

            //bool ck = CheckErrerCode(text);

            //if (!ck)
            //    throw new Exception("条形码字符不合要求，不能是汉字或全角字符");

            string barstring = BuildBarString(mycode);
            if (!isShowMode)
                return KiCode128CZ90(barstring, iHight);//垂直条码
            else return KiCode128C(barstring, iHight);//平行条码
        }

        /// <summary>
        /// 建立条码字符串
        /// </summary>
        /// <param name="tex">条码内容</param>
        /// <returns></returns>
        private static string BuildBarString(string tex)
        {

            string barstart = "bbsbssbssss";    //码头

            string barbody = "";                //码身

            string barcheck = "";               //码检

            string barend = "bbsssbbbsbsbb";    //码尾

            int checkNum = 104;

            //循环添加码身,计算码检

            for (int i = 1; i <= tex.Length; i++)
            {

                int index = (int)tex[i - 1] - 32;

                checkNum += (index * i);

                barbody += AddSimpleTag(index);//加入字符值的条码标记

            }

            //码检值计算

            barcheck = AddSimpleTag(int.Parse(Convert.ToDouble(checkNum % 103).ToString("0")));

            string barstring = barstart + barbody + barcheck + barend;

            return barstring;

        }

        //增加一个条码标记
        private static string AddSimpleTag(int CodeIndex)
        {

            string res = "";
            /// <summary>1-4的条的字符标识 </summary>
            string[] TagB = { "", "b", "bb", "bbb", "bbbb" };
            /// <summary>1-4的空的字符标识 </summary>
            string[] TagS = { "", "s", "ss", "sss", "ssss" };

            string[] Code128List = new string[] {
 
                "212222","222122","222221","121223","121322","131222","122213","122312","132212","221213",
 
                "221312","231212","112232","122132","122231","113222","123122","123221","223211","221132",
 
                "221231","213212","223112","312131","311222","321122","321221","312212","322112","322211",
 
                "212123","212321","232121","111323","131123","131321","112313","132113","132311","211313",
 
                "231113","231311","112133","112331","132131","113123","113321","133121","313121","211331",
 
                "231131","213113","213311","213131","311123","311321","331121","312113","312311","332111",
 
                "314111","221411","431111","111224","111422","121124","121421","141122","141221","112214",
 
                "112412","122114","122411","142112","142211","241211","221114","413111","241112","134111",
 
                "111242","121142","121241","114212","124112","124211","411212","421112","421211","212141",
 
                "214121","412121","111143","111341","131141","114113","114311","411113","411311","113141",
 
                "114131","311141","411131","211412","211214","211232" };

            string tag = Code128List[CodeIndex];

            for (int i = 0; i < tag.Length; i++)
            {

                string temp = "";

                int num = int.Parse(tag[i].ToString());

                if (i % 2 == 0)
                {

                    temp = TagB[num];
                }

                else
                {
                    temp = TagS[num];
                }
                res += temp;
            }

            return res;

        }

        /// <summary>
        /// 检查条形码文字是否合条件(不能是汉字或全角字符)
        /// </summary>
        /// <param name="cktext"></param>
        /// <returns></returns>
        private static bool CheckErrerCode(string cktext)
        {
            foreach (char c in cktext)
            {
                byte[] tmp = System.Text.UnicodeEncoding.Default.GetBytes(c.ToString());
                if (tmp.Length > 1)
                    return false;
            }
            return true;
        }

        /// <summary>生成条码128码 垂直</summary>
        /// <param name="BarString">条码模式字符串</param> //Format32bppArgb
        /// <param name="Height">生成的条码高度</param>
        /// <returns>条码图形</returns>
        private static Bitmap KiCode128CZ90(string BarString, int iWidth)
        {
            Bitmap b = new Bitmap(iWidth, BarString.Length, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
            //using (Graphics grp = Graphics.FromImage(b))
            //{
            try
            {
                char[] cs = BarString.ToCharArray();
                for (int i = 0; i < cs.Length; i++)
                {
                    for (int j = 0; j < iWidth; j++)
                    {
                        if (cs[i] == 'b')
                        {
                            b.SetPixel(j, i, Color.Black);
                        }
                        else
                        {
                            b.SetPixel(j, i, Color.White);
                        }

                    }

                }
                //grp.DrawString(text, SystemFonts.CaptionFont, Brushes.Black, new PointF(leftEmpty, b.Height - botEmpty));
                return b;
            }
            catch
            {
                return null;
            }
            //}
        }
        /// <summary>生成条码128码 平行 </summary>
        /// <param name="BarString">条码模式字符串</param> //Format32bppArgb
        /// <param name="Height">生成的条码高度</param>
        /// <returns>条码图形</returns>
        private static Bitmap KiCode128C(string BarString, int _Height)
        {
            Bitmap b = new Bitmap(BarString.Length, _Height, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
            //using (Graphics grp = Graphics.FromImage(b))
            //{
            try
            {
                char[] cs = BarString.ToCharArray();
                for (int i = 0; i < cs.Length; i++)
                {
                    for (int j = 0; j < _Height; j++)
                    {
                        if (cs[i] == 'b')
                        {
                            b.SetPixel(i, j, Color.Black);
                        }
                        else
                        {
                            b.SetPixel(i, j, Color.White);
                        }

                    }

                }
                //grp.DrawString(text, SystemFonts.CaptionFont, Brushes.Black, new PointF(leftEmpty, b.Height - botEmpty));
                return b;
            }
            catch
            {
                return null;
            }
            //}
        }
        #endregion


        #region   GetCode39_1    条形码图片 Code39码     垂直不行
        public static void GetBarCodeBitmap_Code39_1(string mycode, string strFilePath, int iHight, int iy, bool isShowNum)
        {
            if (!string.IsNullOrEmpty(mycode))
            {
                Bitmap BMP = isShowNum ? GetCode39_1(mycode) : GetCode39Z90_1(mycode);     //true横false竖

                BMP.Save(strFilePath, ImageFormat.Jpeg);
                BMP.Dispose();
            }
            else
            {

                Bitmap BMP = new Bitmap(30, iHight, System.Drawing.Imaging.PixelFormat.Format64bppPArgb);
                Graphics G = Graphics.FromImage(BMP);
                G.TextRenderingHint = TextRenderingHint.AntiAlias;
                G.Clear(Color.White);

                //未給參數時顯示的提示內容
                G.DrawString("无条码产生", new Font("宋体", 12, FontStyle.Regular), SystemBrushes.WindowText, new PointF(0, 20));
                //BMP.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                G.Dispose();

                BMP.Dispose();
            }
        }

        private static Bitmap GetCode39_1(string strSource)
        {
            int x = 5;
            int y = 0;
            int WidLength = 2;
            int NarrowLength = 1;
            int BarCodeHeight = 50;
            int intSourceLength = strSource.Length;
            string strEncode = "010010100";

            string AlphaBet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"; //Code39的字母

            #region  string[] Code39
            string[] Code39 = 
            {
                   /**//* 0 */ "000110100",
                   /**//* 1 */ "100100001",
                   /**//* 2 */ "001100001",
                   /**//* 3 */ "101100000",
                   /**//* 4 */ "000110001",
                   /**//* 5 */ "100110000",
                   /**//* 6 */ "001110000",
                   /**//* 7 */ "000100101",
                   /**//* 8 */ "100100100",
                   /**//* 9 */ "001100100",
                   /**//* A */ "100001001",
                   /**//* B */ "001001001",
                   /**//* C */ "101001000",
                   /**//* D */ "000011001",
                   /**//* E */ "100011000",
                   /**//* F */ "001011000",
                   /**//* G */ "000001101",
                   /**//* H */ "100001100",
                   /**//* I */ "001001100",
                   /**//* J */ "000011100",
                   /**//* K */ "100000011",
                   /**//* L */ "001000011",
                   /**//* M */ "101000010",
                   /**//* N */ "000010011",
                   /**//* O */ "100010010",
                   /**//* P */ "001010010",
                   /**//* Q */ "000000111",
                   /**//* R */ "100000110",
                   /**//* S */ "001000110",
                   /**//* T */ "000010110",
                   /**//* U */ "110000001",
                   /**//* V */ "011000001",
                   /**//* W */ "111000000",
                   /**//* X */ "010010001",
                   /**//* Y */ "110010000",
                   /**//* Z */ "011010000",
                   /**//* - */ "010000101",
                   /**//* . */ "110000100",
                   /**//*' '*/ "011000100",
                   /**//* $ */ "010101000",
                   /**//* / */ "010100010",
                   /**//* + */ "010001010",
                   /**//* % */ "000101010",
                   /**//* * */ "010010100"
            };
            #endregion

            strSource = strSource.ToUpper();

            Bitmap objBitmap = new Bitmap(
              ((WidLength * 3 + NarrowLength * 7) * (intSourceLength + 2)) + (x * 2),
              BarCodeHeight + (y * 2));

            Graphics objGraphics = Graphics.FromImage(objBitmap);
            objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; //插值模式
            objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;//文本呈现提示
            objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;     //平滑模式
            objGraphics.FillRectangle(Brushes.White, 0, 0, objBitmap.Width, objBitmap.Height);

            for (int i = 0; i < intSourceLength; i++)
            {
                if (AlphaBet.IndexOf(strSource[i]) == -1 || strSource[i] == '*')
                {
                    objGraphics.DrawString("含有非法字符",
                     SystemFonts.DefaultFont, Brushes.Red, x, y);
                    return objBitmap;
                }
                strEncode = string.Format("{0}0{1}", strEncode,
                 Code39[AlphaBet.IndexOf(strSource[i])]);
            }

            strEncode = string.Format("{0}0010010100", strEncode);

            int intEncodeLength = strEncode.Length;
            int intBarWidth;



            for (int i = 0; i < intEncodeLength; i++)
            {
                intBarWidth = strEncode[i] == '1' ? WidLength : NarrowLength;
                objGraphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White,
                  x, y, intBarWidth, BarCodeHeight);
                x += intBarWidth;
            }
            return objBitmap;
        }

        private static Bitmap GetCode39Z90_1(string strSource)
        {
            int x = 5;
            int y = 0;
            int WidLength = 2;
            int NarrowLength = 1;
            int BarCodeHeight = 50;
            int intSourceLength = strSource.Length;
            string strEncode = "010010100";

            string AlphaBet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*"; //Code39的字母

            #region  string[] Code39
            string[] Code39 = 
            {
                   /**//* 0 */ "000110100",
                   /**//* 1 */ "100100001",
                   /**//* 2 */ "001100001",
                   /**//* 3 */ "101100000",
                   /**//* 4 */ "000110001",
                   /**//* 5 */ "100110000",
                   /**//* 6 */ "001110000",
                   /**//* 7 */ "000100101",
                   /**//* 8 */ "100100100",
                   /**//* 9 */ "001100100",
                   /**//* A */ "100001001",
                   /**//* B */ "001001001",
                   /**//* C */ "101001000",
                   /**//* D */ "000011001",
                   /**//* E */ "100011000",
                   /**//* F */ "001011000",
                   /**//* G */ "000001101",
                   /**//* H */ "100001100",
                   /**//* I */ "001001100",
                   /**//* J */ "000011100",
                   /**//* K */ "100000011",
                   /**//* L */ "001000011",
                   /**//* M */ "101000010",
                   /**//* N */ "000010011",
                   /**//* O */ "100010010",
                   /**//* P */ "001010010",
                   /**//* Q */ "000000111",
                   /**//* R */ "100000110",
                   /**//* S */ "001000110",
                   /**//* T */ "000010110",
                   /**//* U */ "110000001",
                   /**//* V */ "011000001",
                   /**//* W */ "111000000",
                   /**//* X */ "010010001",
                   /**//* Y */ "110010000",
                   /**//* Z */ "011010000",
                   /**//* - */ "010000101",
                   /**//* . */ "110000100",
                   /**//*' '*/ "011000100",
                   /**//* $ */ "010101000",
                   /**//* / */ "010100010",
                   /**//* + */ "010001010",
                   /**//* % */ "000101010",
                   /**//* * */ "010010100"
            };
            #endregion

            strSource = strSource.ToUpper();

            Bitmap objBitmap = new Bitmap(
              BarCodeHeight + (y * 2), ((WidLength * 3 + NarrowLength * 7) * (intSourceLength + 2)) + (x * 2));

            Graphics objGraphics = Graphics.FromImage(objBitmap);
            objGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; //插值模式
            objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;//文本呈现提示
            objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;     //平滑模式

            objGraphics.FillRectangle(Brushes.White, 0, 0, objBitmap.Height, objBitmap.Width);

            for (int i = 0; i < intSourceLength; i++)
            {
                if (AlphaBet.IndexOf(strSource[i]) == -1 || strSource[i] == '*')
                {
                    objGraphics.DrawString("含有非法字符",
                     SystemFonts.DefaultFont, Brushes.Red, y, x);
                    return objBitmap;
                }
                strEncode = string.Format("{0}0{1}", strEncode,
                 Code39[AlphaBet.IndexOf(strSource[i])]);
            }

            strEncode = string.Format("{0}0010010100", strEncode);

            int intEncodeLength = strEncode.Length;
            int intBarWidth;



            for (int i = 0; i < intEncodeLength; i++)
            {
                intBarWidth = strEncode[i] == '1' ? WidLength : NarrowLength;
                objGraphics.FillRectangle(i % 2 == 0 ? Brushes.Black : Brushes.White,
                   y, x, BarCodeHeight, intBarWidth);
                x += intBarWidth;
            }
            return objBitmap;
        }
        #endregion

    }
   

}